package user_dao

import (
	"context"
	"ebip/internel/repository/dao"
	"errors"
	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
)

// @Description
// @Author 代码小学生王木木

var ErrUserDuplicate = errors.New("用户名冲突")

func NewIUserDAO(db *gorm.DB) IUserDAO {
	return &gormUserDAO{
		db: db,
	}
}

type gormUserDAO struct {
	db *gorm.DB
}

func (g *gormUserDAO) FindByID(ctx context.Context, id int64) (dao.UserMode, error) {
	//TODO implement me
	panic("implement me")
}

func (g *gormUserDAO) FindByUserName(ctx context.Context, username string) (dao.UserMode, error) {
	var user dao.UserMode
	err := g.db.WithContext(ctx).Model(&dao.UserMode{}).Where(
		"username=?", username).First(&user).Error
	return user, err
}

func (g *gormUserDAO) Insert(ctx context.Context, mode dao.UserMode) (int64, error) {
	err := g.db.WithContext(ctx).Model(&dao.UserMode{}).Create(&mode).Error
	if mysqlErr, ok := err.(*mysql.MySQLError); ok {
		const uniqueConflictsErrNo uint16 = 1062
		if mysqlErr.Number == uniqueConflictsErrNo {
			// 邮箱冲突 or 手机号码冲突
			return 0, ErrUserDuplicate
		}
	}
	if err != nil {
		return 0, err
	}
	return int64(mode.ID), nil
}
